package com.training.android.currencyconverter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class CurrencyConvertorActivity extends Activity {
	/** Called when the activity is first created. */

	Spinner fromSpinner, toSpinner;
	Button calculateButton;
	EditText fromEditText, toEditText;

	double[] currencyRate = new double[3];

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initViewComponents();
		initCurrencyRate();

	}

	public void initCurrencyRate() {
		currencyRate[0] = 1.0;
		currencyRate[1] = 55.6792873;
		currencyRate[2] = 68.123608;
	}

	public void initViewComponents() {

		fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
		toSpinner = (Spinner) findViewById(R.id.toSpinner);
		loadSpinners();

		calculateButton = (Button) findViewById(R.id.calculateButton);
		calculateButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				calculateButtonClicked(v);
			}
		});

		fromEditText = (EditText) findViewById(R.id.fromEditText);
		toEditText = (EditText) findViewById(R.id.toEditText);
		toEditText.setKeyListener(null);
	}

	public void loadSpinners() {

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.currency_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		fromSpinner.setAdapter(adapter);
		toSpinner.setAdapter(adapter);

	}

	public void calculateButtonClicked(View v) {

		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(fromEditText.getWindowToken(), 0);

		int fromPosition = fromSpinner.getSelectedItemPosition();
		int toPosition = toSpinner.getSelectedItemPosition();
		double fromValue = 0;
		String str = fromEditText.getText().toString();

		if (str != null && str.length() > 0) {
			fromValue = Double.valueOf(str);
		}

		Toast.makeText(getApplicationContext(), String.valueOf(fromValue),
				Toast.LENGTH_SHORT);

		double result = (fromValue * currencyRate[fromPosition])
				/ currencyRate[toPosition];

		toEditText.setText(String.valueOf(result));

	}
}